<script setup>
// import { find, includes } from 'lodash-es';
import { useMain } from '@/store/app.js';
import dayjs from 'dayjs';
import { useRequest, useWatch } from '@/hooks';
import { useResetForm } from '@/hooks/tool.js';
import { getEngTypesByCode, getEnergyFlow, getAreaList, getBuildingByArea } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';
import EnergyType from '@/components/EnergyType.vue/';

const { projectType } = useMain();
const queryForm = ref(null);
const activeName = ref(null);
const isNoData = ref(true);
const radio = ref(projectType);

const dateRange = ref([
  dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
  dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
]);
const cascader = ref();
const cascaderProps = ref({
  emitPath: true,
  checkStrictly: true,
  label: 'areaName',
  value: 'areaName',
});
const queryParams = ref({
  dateStart: dateRange.value[0],
  dateEnd: dateRange.value[1],
  energyType: null,
  enterpriseCode: '',
  projectType: radio.value,
});
const sankeyOpts = ref({
  tooltip: {
    trigger: 'item',
    triggerOn: 'mousemove',
    formatter: function (params) {
      return params.data.value === null ? '' : `${params.name} (${params.value})`;
    }
  },
  series: {
    type: 'sankey',
    layout: 'none',
    layoutIterations: 0,
    label: {
      color: '#7f889a',
      formatter: function (params) {
        return params.data.value === null ? '' : `${params.name} (${params.value})`;
      },
    },
    emphasis: {
      focus: 'adjacency',
    },
    data: [],
    links: [],
  },
});

const insParams = ref({
  isStage: '1',
  areaName: null,
  projectType: radio.value,
});
const [res, loading, runSankey] = useRequest(getEnergyFlow, {
  defaultParams: [queryParams.value],
  manual: true,
  onSuccess: res => {
    isNoData.value = res.data?.links?.[0]?.value ? false : true;
    sankeyOpts.value.series.data = res.data?.data ?? [];
    sankeyOpts.value.series.links = res.data?.links ?? [];
  },
});
const [areaList,,areaRun] = useRequest(getAreaList, {
  defaultParams: [{}],
  onSuccess: res => {
    cascader.value = res.data?.[0]?.areaName ?? null;
    insParams.value.areaName = cascader.value;
    runIns(insParams.value);
  },
});
const [institutionList, , runIns] = useRequest(getBuildingByArea, {
  defaultParams: [{}],
  manual: true,
  onSuccess: res => {
    queryParams.value.enterpriseCode = res.data?.[0]?.enterpriseCode ?? null;
    runEngType({ enterpriseCode: queryParams.value.enterpriseCode, projectType: radio.value, allType:false});
  },
});
const [engTypeList, , runEngType] = useRequest(getEngTypesByCode, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      activeName.value = res.data?.[0]?.id + '' ?? null;
      queryParams.value.energyType = res.data?.[0]?.id ?? null;
      runSankey(queryParams.value);
    }
  },
});

const changeType = val => {
  //调用接口
  queryParams.value.energyType = val;
  runSankey(queryParams.value);
};

const dateChange = val => {
  queryParams.value.dateStart = val?.[0] ?? null;
  queryParams.value.dateEnd = val?.[1] ?? null;
  // if (null === queryParams.value.energyType) {
  //   queryParams.value.energyType = 2;
  // }
};
const cascaderChange = bool => {
  if (!bool) {
    insParams.value.areaName = cascader.value.join('/');
    runIns(insParams.value);
  }
};

const handleQuery = () => {
  runEngType({ enterpriseCode: queryParams.value.enterpriseCode, projectType: radio.value, allType:false});
};
const resetQuery = () => {
  useResetForm(queryForm);
  areaRun({})
  handleQuery();
};
useWatch(
  radio,
  n => {
    insParams.value.projectType = n;
    runIns(insParams.value);
    queryParams.value.projectType = n;
    runSankey(queryParams.value);
  },
  // { immediate: true },
);
</script>

<template>
  <div class="app-container">
    <div class="u-df-st u-p20 u-mb20 u-base-fg">
      <el-form v-model="queryParams" inline>
        <el-form-item>
          <el-radio-group v-model="radio" size="small" class="radio">
            <el-radio-button label="JC">监测机构</el-radio-button>
            <el-radio-button label="TG">托管机构</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="行政区划">
          <el-cascader
            v-model="cascader"
            :props="cascaderProps"
            :options="areaList"
            placeholder="请选择行政区划"
            size="small"
            class="u-w100"
            clearable
            @visible-change="cascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="enterpriseCode" label="机构名称">
          <el-select
            v-model="queryParams.enterpriseCode"
            placeholder="请输入机构名称"
            filterable
            size="small"
            class="u-w100"
            clearable
          >
            <el-option
              v-for="(val, index) in institutionList"
              :key="`${val.enterpriseCode}-${index}`"
              :label="val.enterpriseName"
              :value="val.enterpriseCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="dateStart" label="选择时间">
          <el-form-item prop="dateEnd">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              key="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              clearable
              align="left"
              style="width: 240px"
              @change="dateChange"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button type="primary" size="small" plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="u-df-spb">
      <div
        class="u-base-fg u-fs16"
        style="width: calc(70% - 5px); border-bottom: 2px solid #374468; padding: 13px 20px"
      >
        能源流向分布图
      </div>
      <EnergyType
        :engList="engTypeList"
        @changeType="changeType"
        style="width: calc(30% - 5px); padding-left: 20px; padding-right: 20px"
      ></EnergyType>
    </div>
    <div class="chart-box">
      <CECharts v-if="!isNoData" v-loading="loading" :options="sankeyOpts" :style="{height:res?.links?.length>40?res.links?.length+'0px':'100%'}" />
      <div v-else class="u-df-ct u-fs14 u-mt20 u-sec-text">暂无数据</div>
    </div>

  </div>
</template>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

.chart-box {
  box-shadow: none;
  min-height:calc(100% - 150px);
  // height: 3000px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
